const { IncAndExp } = require('../../../model/incAndExp/incAndExp');

function getdate(times) {
    var now = new Date(times),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
    return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}


module.exports = async (req, res) => {
    // 获取post参数
    let pageSize = req.fields.pageSize
    let currentPage = req.fields.current

    let data = []
    if (!req.fields.data) {
        data = await IncAndExp.find().sort('-createTime').skip((currentPage - 1) * pageSize).limit(pageSize);
    } else {
        let { name, label, type, createTime, username, phone } = req.fields.data
        // 一天的毫秒数
        let MillisecondsADay = 24 * 60 * 60 * 1000;
        data = await IncAndExp.find({
            'username': new RegExp(username, 'i'),
            'phone': new RegExp(phone, 'i'),
            'name': new RegExp(name, 'i'),
            "type.value": type || new RegExp(),
            'createTime': {
                $lte: createTime ? parseInt(new Date(createTime).getTime()) : Infinity,
                $gt: createTime ? parseInt(new Date(createTime).getTime() - MillisecondsADay) : 0,
            },
            'label': label == undefined ? { $in: [0, 1] } : label
        }).sort('-createTime').skip((currentPage - 1) * pageSize).limit(pageSize);
    }
    let totalCount = data.length
    let list = data.map((item) => {
        return {
            id: item.id,
            username: item.username,
            phone: item.phone,
            name: item.name,
            type: item.type,
            label: item.label,
            price: item.price,
            createTime: getdate(item.createTime),
            notes: item.notes,
            budget: item.budget,
            balance: item.balance
        }
    })
    res.send({
        'code': 0, data: {
            data: list,
            totalCount
        },
    });
}